//
//  CZUserAccount.swift
//  WHWeiBo
//
//  Created by Li Changjian on 16/7/10.
//  Copyright © 2016年 Li Changjian. All rights reserved.
//

import UIKit


let userAccountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")

class CZUserAccount: NSObject ,NSCoding{
/// 用户授权的唯一票据
    var access_token: String?
/// access_token的生命周期   //设置为String会崩
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expires_date = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
/// accessToken的过期日期
    var expires_date: NSDate?
/// 授权用户的UID
    var uid: Int64 = 0
/// 用户名
    var name: String?
/// 用户头像url
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    // MARK: - 重写descrition属性
    override var description: String {
        let keys = ["access_token", "expires_in", "uid","name","avatar_large",]
        return dictionaryWithValuesForKeys(keys).description
    }
    // MARK: - 归档保存用户账号信息
    func saveUserAccount() -> Bool {
        
       return NSKeyedArchiver.archiveRootObject(self, toFile: userAccountPath)
    }
    // MARK: - 从沙盒中解档用户账号信息
    class func loadUserAccount() -> CZUserAccount? {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountPath) as? CZUserAccount
    }
    
    
    
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    // MARK: - 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    // MARK: - 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}
